<template>
  <div class="lyric" ref="lyric">
    <div>
      <p
        v-for="(item, index) in currentLyric"
        :key="index"
        v-text="item.txt"
        :class="`${Index === index ? 'active' : ''}`"
      ></p>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Lyric from "lyric-parser";
export default {
  mounted() {
    this.$api.lyric({ id: this.Nowplay }).then(res => {
      this.currentLyric = new Lyric(res).lines;
      this.currentTime = this.audio.currentTime;
      window.setInterval(() => {
        this.contol();
      }, 1000);
    });
  },
  methods: {
    contol() {
      var n;
      this.currentLyric.find((item, index) => {
        if (parseInt(item.time / 1000) === Math.round(this.audio.currentTime)) {
          n = index;
          return true;
        }
        return false;
      });
      if (n && n !== this.Index) {
        this.Index = n;
        let index = this.Index - 3;
        index < 0 ? (index = 0) : null;
        this.$refs.lyric && (this.$refs.lyric.scrollTop = index * 30);
      }
    }
  },
  data() {
    return {
      currentLyric: "",
      Index: 0, //当前行
      currentTime: "" //当前时间
    };
  },
  computed: {
    ...mapState(["Nowplay", "audio", "play"])
  }
};
</script>

<style lang="less" scoped>
.lyric {
  overflow: auto;
  height: 300px;
  margin-top: 20px;
  line-height: 30px;
  font-size: 14px;
  transform: all 0.2s;
  .active {
    color: white;
  }
}
</style>
